<?php
class AjaxAction extends CommonAction {
	//地区
	public function getRegion(){
		$father_id = isset($_POST['fid'])?intval($_POST['fid']):0;
		$db=M('Region');
		$data = $db->where(array('father_id'=>$father_id))->select();
		$str = '<option value="">-请选择地区-</option>';
		foreach($data as $k => $v){
			$str .= '<option value="'.$v['region_id'].'">'.$v['region_name'].'</option>';
		}
		if(count($data)>0){
			$str = '<select style="width:auto; display:inline; margin-right:8px; margin-bottom:5px;" class="form-control"  id="select" datatype="*" onchange="sendRegion(this)" name="area[]">'.$str.'</select>';
		}else{
			$str='';
		}
		echo $str;
	}
	
	public function setRegion($return = false){
		$db=M('Region');
		$area = explode(',', trim($this->_post('area'),','));
		$ret = "";
		foreach($area as $skey => $sid){
			$father_id = $skey == 0 ? 0 : $area[$skey - 1];
			$data = $db->where(array('father_id'=>$father_id))->select();
			$str = '<option value="">-请选择-</option>';
			foreach($data as $k => $v){
				$selectstr = "";
				if($sid == $v['region_id']){
					$selectstr = 'selected="selected"'; 
				}
				$str .= '<option '.$selectstr.' value="'.$v['region_id'].'">'.$v['region_name'].'</option>';
			}
			if(count($data)>0){
				$str = '<select style="width:auto; display:inline; margin-right:8px;" class="form-control" id="select" datatype="*" onchange="sendRegion(this)" name="area[]">'.$str.'</select>';
			}else{
				$str='';
			}
			$ret .= $str;
		}
		$_POST['fid'] = $sid;
		if($return){return $ret;}
		echo $ret.$this->getRegion();
		
		
	}
	
	//根据地区获取供货商下拉列表
	public function getSupplier(){
		$area = isset($_POST['area'])?$_OST['area']:array();
		$db=M('Supplier');
		if(count($_POST['area']) == 1){
			
		}
		$data = $db->where("area like '%,".implode(',',$_POST['area']).",%' and site_id = ".__SITEID__)->select();
		$str = '';
		foreach($data as $k => $v){
			$str .= '<option value="'.$v['id'].'">'.$v['susername'].'</option>';
		}
		if(count($data)>0){
			$str = '<select onChange="getProduct(this);" style="width:auto; display:inline; margin-right:8px; margin-bottom:5px;" class="form-control"  id="select" datatype="*"  name="supplier_id">'.$str.'</select>';
		}else{
			$str='当前地区没有供货商或服务商';
		}
		echo $str;
	}
	
	//注册
	public function reg(){
		$this->display(TMPL_PATH.'Common/reg.html');
	}
	//登录
	public function login(){
		$this->display('Ajax:login');
	}
	//获取规格
	public function getSKU(){
		$id = $this->_get('id');
		$productModel = D('Product');
		//$skuList = $productModel->getSKUListById($id);
		$SKU = $productModel->getSKUById($id);
		echo $SKU;
	}
	
	//提醒关注，微信端适用
	
	public function subscribe(){
		if($this->is_weixin() && $this->siteInfo['is_wxLogin'] == 2){
			$memberdb = D('Member');
			$config = unserialize($this->siteInfo['qrcodesetting']);
			$this->subscribeLink = $config['subscribeLink'];
			
			$this->subscribeImage = $config['subscribeImage'];
			//dump($config);
			$affid = intval($_COOKIE['aff_id']);
			$this->userInfo = $memberdb -> where(array('id' => $this->memberInfo['id'])) -> find();
			$this->parentUserInfo = $memberdb -> where(array('id' => $this->memberInfo['pid'])) -> find();
			
			$this->display('subscribe');
		}else{
			exit('');
		}
	}
	
	
	public function subscribeaff(){
		if($this->is_weixin() && $this->siteInfo['is_wxLogin'] == 2){
			$memberdb = D('Member');
			$config = unserialize($this->siteInfo['qrcodesetting']);
			$this->subscribeLink = $config['subscribeLink'];
			
			$this->subscribeImage = $config['subscribeImage'];
			//dump($config);
			$affid = intval($_COOKIE['aff_id']);
			$this->userInfo = $memberdb -> where(array('id' => $this->memberInfo['id'])) -> find();
			$this->parentUserInfo = $memberdb -> where(array('id' => $affid)) -> find();
			
			$this->display('subscribe');
		}else{
			exit('');
		}
	}
	
	
	
	
	//提醒关注，微信端适用
	public function getJsSdk(){
		if ($this->is_weixin()) {
		    //微信分享接口
			Vendor('Weixin.Weixin'); 
			$d['token'] = getSysVal('token');
			$d['appid'] = getSysVal('appid');
			$d['appsecret'] = getSysVal('appsecret');
			$this->weixin = new WeixinChat($d);
			echo json_encode($this -> weixin -> getSignPackage('', 1, $this->_post('url')));
			
		}else{
			exit('');
		}
	}
	
	public function getStockAndSale(){
		$id = $this-> _get('id') ? $this->_get('id'):0;
		$ret = array('sale' => 0, 'stock' => 0);
		if($id == 0){
			exit(json_encode($ret));
		}
		$ret['sale'] = (int)/*M('Sale') -> where(array('product_id' => $id)) -> sum('num') + */M('Product') -> where(array('id' => $id)) -> getField('salecount');
		$ret['stock'] = M('Product') -> where(array('id' => $id)) -> getField('stocks');
		$ret['zan'] = M('Zan') -> where(array('product_id' => $id)) -> count();
		echo json_encode($ret);
	}
	
	//商品点赞
	public function ProductZan(){
		$pid = $this->_get('id')?$this->_get('id'):0;
		if($pid == 0){
			$this->error('参数错误！');
		}
		//是否点过
		$zanDB = M('Zan');
		$ret = array();
		$info = $zanDB -> where(array('product_id' => $pid, 'member_id' => $this->memberInfo['id'])) -> find();
		if($info){
			$this->error('您已经点过！');
		}else{
			$data['product_id'] = $pid;
			$data['member_id'] = $this->memberInfo['id'];
			$data['datetime'] = time();
			$re = $zanDB -> add($data);
			if($re){
				$ret['data'] = $zanDB -> where(array('product_id' => $pid)) -> count();
				$ret['status'] = 1;
				$ret['info'] = '点赞成功！';
				echo json_encode($ret);
			}else{
				$this->error($zanDB -> getError());
			}
		}
	}
	//商品点赞
	public function NewsZan(){
		$pid = $this->_post('id')?$this->_post('id'):0;
		if($pid == 0){
			$this->error('参数错误！');
		}
		//是否点过
		$zanDB = M('Zan');
		$ret = array();
		$info = $zanDB -> where(array('news_id' => $pid, 'member_id' => $this->memberInfo['id'])) -> find();
		if($info){
			$this->error('您已经点过！');
		}else{
			$data['news_id'] = $pid;
			$data['member_id'] = $this->memberInfo['id'];
			$data['datetime'] = time();
			$re = $zanDB -> add($data);
			if($re){
				$ret['data'] = $zanDB -> where(array('news_id' => $pid)) -> count();
				M('News') -> where(array('id' => $pid)) -> save(array('zan' => $ret['data']));
				$ret['status'] = 1;
				$ret['info'] = '点赞成功！';
				echo json_encode($ret);
			}else{
				$this->error($zanDB -> getError());
			}
		}
	}
	//商品点赞
	public function EvaluateZan(){
		$pid = $this->_post('id')?$this->_post('id'):0;
		if($pid == 0){
			$this->error('参数错误！');
		}
		//是否点过
		$zanDB = M('Zan');
		$ret = array();
		$info = $zanDB -> where(array('evaluate_id' => $pid, 'member_id' => $this->memberInfo['id'])) -> find();
		if($info){
			$this->error('您已经点过！');
		}else{
			$data['evaluate_id'] = $pid;
			$data['member_id'] = $this->memberInfo['id'];
			$data['datetime'] = time();
			$re = $zanDB -> add($data);
			if($re){
				$ret['data'] = $zanDB -> where(array('evaluate_id' => $pid)) -> count();
				M('Evaluate') -> where(array('id' => $pid)) -> save(array('zan' => $ret['data']));
				$ret['status'] = 1;
				$ret['info'] = '点赞成功！';
				echo json_encode($ret);
			}else{
				$this->error($zanDB -> getError());
			}
		}
	}
	
	
	public function getNensZanAndClick(){
		$id = $this->_post('id');
		$map['id'] = $id;
		$db = M('News');
		$data = $db -> where($map) -> Field('zan, click') -> find();
		echo json_encode($data);
	}
	
	
	//写入分享日志 
	public function weixinshare(){
		if($this->_post('url')){
			$data['site_id'] = __SITEID__;
			$data['member_id'] = $this->memberInfo['id'];
			$data['url'] = $this->_post('url');
			$data['datetime'] = time();
			M('Weixinshare') -> add($data);
		}
    }
	
	//生成二维码
	public function createaffqr(){
		ignore_user_abort(true);
		$id = $this->_get('id');
		//$user = M('Member') -> where(array('id' => $id)) -> find();
		$afflist = $payment = M('Affiliatesetting') -> where(array('site_id' => __SITEID__, 'status' => 1)) -> select();
		foreach($afflist as $v){
			import("@.ORG.Affiliate.".$v['classname']);
			$class = $v['classname']; 
			$Threelevel = new $class(0, __SITEID__,$id);
		}
		
		$user = M('Member') -> where(array('id' => $id, 'site_id' => __RELATEID__)) -> find();
		createaffqr($user);
	}
	
	
	
	
	
	
	public function getCartView(){
		if($this->_request('id')){
			$productModel=D('Product');
			$id = $this->_request('id');
			$info = $productModel->where(array('id'=>$id))->find();
			$skuList=$productModel->getSKUListById($id);
			$SKU=$productModel->getSKUById($id);
			$this->assign('skuList',$skuList);
			$this->assign('SKU',$SKU);
			$this->assign($info);
			echo $this->fetch();
		}
	}
	
	
	
	//获取分类和商品列表
	public function getCategoryListOrProductList(){
		$Action = A('Home/Product_category');
		//$_GET['id'] = $this->_post('category_id');
		
		
		
		$Action->initView();
		
		
		
		$Action->category_id = intval($this->_post('category_id')) > 0 ? intval($this->_post('category_id')) : $_COOKIE['prevcid'];
		$Action->listmap .= " and p.status > 0 and p.site_id=".__SITEID__;
		
		
		if($this->_post('supplier_id') && $this->_post('supplier_id') != ''){
			$Action->listmap.=' and (p.supplier_id in('.$this->_post('supplier_id').'))';
		}
		
		
		if($this->_post('area')){
				$Suppliersql = M('Supplier') -> where("area like '%,".implode(',', $this->_post('area')).",%'") -> Field('id as supplier_id') -> buildSql();
				if($this->_post('supplier_id') && $this->_post('supplier_id') != ''){
					$Action->listmap.=' and (p.supplier_id in('.$this->_post('supplier_id').'))';
				}else{
					$Action->listmap.=' and (p.supplier_id in('.$Suppliersql.'))';
				}
				
				$Action -> assign('area', ",".implode(',', $this->_post('area')).",");
				
				//$Action -> assign('areaRet', $this->setRegion(true));
				
		}
		
		
		if($this->_post('sendRegion') > 0){
			$Action -> assign('sendRegion', $this->_post('sendRegion'));
		}else{
			$Action -> assign('sendRegion', 0);
		}
		
		
		
		
		
		$Action->ajax = true;
		
		
		if($_COOKIE['displayall_'.__SITEID__] > 0){
			
			$Action -> _index($Action->category_id);
		}else{
			$Action -> _indexajax($Action->category_id);
		}
		
		
		$Action->cid = $this->_post('cid'); 
		
		$Product_categoryModel=D("Product_category");
			//下级分类,如果没有下级,显示同级
		$subCategory = $Product_categoryModel -> where(array('pid' => $this->_post('cid'),'site_id' => __SITEID__)) -> order('sort') -> select();
		$Action->subCategory = $subCategory;
		
		
		$modules = D('Modules')-> getListToArray(array('id'=> $this->_post('id')),$this->view);
		$Action->assign('v',$modules[0]);
		$content = $Action->fetch(TMPL_PATH.'Home/TemplateDefault/Modules-'.$modules[0]['filename'].C('TMPL_TEMPLATE_SUFFIX'));
		setcookie('prevcid', $Action->category_id, time() + 3600, '/');
		exit($content);
	}
	
	
	//获取等级会员数量
	public function getMemberCount($deep = 0, $member_id = 0){
		$deep = $this->_post('deep');
		$member_id = $this->_post('member_id');
		echo M('Member_member') -> where(array('deep' => $deep, 'member_id' => $member_id)) -> count();
	}
	//获取等级会员数量
	public function getMemberVipCount($deep = 0, $member_id = 0){
		$this->db = D('Member');
		//市场人数统计
		$datacount['a'] = (int)$this->db -> getLevel1Count($member_id, 1, 1);
		//计算八级以内市场人数
		$datacount['c'] = (int)$this->db -> getLevel1Count($member_id, 1, 100);
		$datacount['b'] = $datacount['c'] - $datacount['a'];
		
		echo json_encode($datacount);
	}
	//
	public function getOrderAff(){
		$member_id = $this->_post('member_id');
		$orderstatus = $this->_post('orderstatus');
		$db = M('Member_member');
		$sql = $db -> where(array('member_id' => $member_id)) -> Field('smember_id as member_id') -> buildSql();
		$orderDb = M('Order');
		echo $orderDb -> where("status in(".$orderstatus.") and member_id in(".$sql.")") -> count();
		//echo $orderDb -> getLastSql();
	}
	
	
	//获取个人中心数据
	public function getAffData(){
		$member_id = $this->_post('member_id');
		//未付款订单财富
		$db = M('Affiliatelog');
		$data['a'] = (float)$db -> where(array('member_id' => $member_id)) -> sum('aff_money');
		//已付款订单财富
		$db = M('Member_account_log');
		$data['b'] = (float)$db -> where(array('member_id' => $member_id, 'pdstate' => 3)) -> sum('changenum');
		//已收货订单财富
		$sql = M('Sql') -> where(array('member_id' => $member_id, 'confirm' => 1)) -> Field('order_id as id') -> buildSql();
		$data['c'] = (float)$db -> where(array('member_id' => $member_id, 'pdstate' => 3, 'order_id' => array('in', $sql))) -> sum('changenum');
		//已完成订单财富
		$data['d'] = (float)$db -> where(array('member_id' => $member_id, 'pdstate' => 3, 'status' => 1)) -> sum('changenum');
		//已提现财富
		$data['e'] = (float)$db -> where(array('member_id' => $member_id, 'pdstate' => 2, 'status' => 1)) -> sum('changenum');
		//可提现财富
		$data['f'] = (float)M('Member') -> where(array('id' => $member_id)) -> getField('money');
		$data['g'] = (float)$data['a']+$data['b'];
		exit(json_encode($data));
	}
	
	
	//异步写入评论
	public function insertEvaluate(){
		if(IS_POST){
			$db = M('Evaluate');
			$_POST['member_id'] = $this->memberInfo['id'];
			if(intval($_POST['member_id']) ==  0){
				$ret['needLogin'] = 1;
			    $ret['status'] = 0;
				$ret['info'] = '请先登录';
				exit(json_encode($ret));
			}
			$_POST['nickname'] = $this->memberInfo['nickname'] == '' ? $this->memberInfo['username'] : $this->memberInfo['nickname'];
			$_POST['site_id'] = __SITEID__;
			$_POST['img_url'] = $this->memberInfo['img_url'];
			$_POST['datetime'] = time();
						$ret = $db -> add($_POST);
			if($ret){
				$this->success('提交成功');
			}else{
				$this->error($db -> getError());
			}
			
		}else{
			$this->error('不能提交空评论');
		}
	}
	//异步写入文章评论
	public function insertEvaluateNews(){
		if(IS_POST){
			$db = M('Evaluate');
			$_POST['member_id'] = $this->memberInfo['id'];
			if(intval($_POST['member_id']) ==  0){
				$ret['needLogin'] = 1;
			    $ret['status'] = 0;
				$ret['info'] = '请先登录';
				exit(json_encode($ret));
			}
			$_POST['status'] = 1;
			$_POST['nickname'] = $this->memberInfo['nickname'] == '' ? $this->memberInfo['username'] : $this->memberInfo['nickname'];
			$_POST['site_id'] = __SITEID__;
			$_POST['img_url'] = $this->memberInfo['img_url'];
			$_POST['datetime'] = time();
			
			$ret = $db -> add($_POST);
			if($ret){
				$this->success('提交成功');
			}else{
				$this->error($db -> getError());
			}
			
		}else{
			$this->error('不能提交空评论');
		}
	}
	
	//异步写入文章评论回复
	public function insertEvaluateNewsReply(){
		if(IS_POST){
			$db = M('Evaluate_reply');
			$_POST['member_id'] = $this->memberInfo['id'];
			if(intval($_POST['member_id']) ==  0){
				$ret['needLogin'] = 1;
			    $ret['status'] = 0;
				$ret['info'] = '请先登录';
				exit(json_encode($ret));
			}
			$_POST['datetime'] = time();
			$_POST['nickname'] = $this->memberInfo['nickname'];
			//$_POST['atnickname'] = $_POST['nickname'];
			if(!$db -> create()){
				$this->error($db -> getError());
			}
			$ret = $db -> add();
			if($ret){
				$this->success('提交成功');
			}else{
				$this->error($db -> getError());
			}
			
		}else{
			$this->error('不能提交空的回复内容');
		}
	}
	
	//异步获取一个产品的评论列表
	public function getEvaluateList(){
		$id = $this->_post('id');
		$evaluateList = M('Evaluate') -> where(array('site_id' => __SITEID__, 'status'=>1, 'product_id' => $id)) -> order('id desc') -> limit('50') -> select();
		$evaluate_replyDB  = M('Evaluate_reply');
		foreach($evaluateList as $k => $v){
			$evaluateList[$k]['reply'] = $evaluate_replyDB -> where(array('evaluate_id' => $v['id'])) -> order('id asc') -> select();
		}
		
		$this->assign('evaluateList', $evaluateList);
		$this->display();
	}
	
	
	//异步获取一个文章的评论列表
	public function getEvaluateListNews(){
		$id = $this->_post('id');
		$evaluateList = M('Evaluate') -> where(array('site_id' => __SITEID__, 'status'=>1, 'news_id' => $id)) -> order('id desc') -> limit('50') -> select();
		$evaluate_replyDB  = M('Evaluate_reply');
		foreach($evaluateList as $k => $v){
			$evaluateList[$k]['reply'] = $evaluate_replyDB -> where(array('evaluate_id' => $v['id'])) -> order('id asc') -> select();
		}
		
		$this->assign('evaluateList', $evaluateList);
		$this->display('getEvaluateList');
	}
	
	
	//获取付款数量
	public function getPayCount(){
		echo (int)M('Sale') -> where(array('product_id' => $this->_post('id'))) -> sum('num') + M('Product') -> where(array('id' => $this->_post('id'))) -> getField('salecount');
	}
	
	//返回分类列表
	public function jdCategories(){
		$pid = $this->_get('pid');
		$Db = M('Product_category');
		$list = $Db -> where(array('site_id' => __SITEID__, 'pid' => $pid)) -> select();
		$this->assign('list', $list);
		$this -> display();
	}
	
	//Ajax获取购买人
	public function GrouppurchaseSale(){
		$virtualSale = M('Grouppurchase') -> where(array('product_id' => $this->_get('product_id'))) -> getField('virtualSale');
		$data = explode(',', $virtualSale);
		$rand = rand(0, count($virtualSale));
		
		
		if($rand <= count($virtualSale)){
			echo $data[$rand];
		}else{
			echo '';
		}
		
		
	}
	
	
	
	
	//用户选择语言 跳转到对应的站点
	public function getSiteBylang(){
		$lang = $this->_get('lang');
		$siteDB = M('site');
		
		$user = $siteDB -> where(array('id' => __RELATEID__)) -> find();
		
	
		
		$site_id = $siteDB->where(array('lang'=>$lang, 'relate_id' => __RELATEID__))->field('id')->find();
		
		if(is_array($site_id)){
			$ret['status'] = 1;
			$ret['data'] = $site_id['id'];
		}else{
			$ret['status'] = 1;
			$ret['data'] = __RELATEID__;
		}
		echo json_encode($ret);
		
	}
	
	//用户选择语言 跳转到对应的站点
	public function getMemberNickname(){
		
		if($this->memberInfo['id']){
			$data = M('Member') -> where(array('id' => $this->memberInfo['id'], 'site_id' => __SITEID__)) -> Field('nickname,img_url')-> find();
			$data['nickname'] = cut_str($data['nickname'], 5, 0);
		}else{
			$data['nickname'] = '';$data['img_url'] = '';
		}
		$data['memberCount'] = M('Member') -> where(array('site_id' => __SITEID__)) -> count();
		echo json_encode($data);
	}
	
	public function createSite(){
		ignore_user_abort();
		$order_id = $this->_get('order_id');
		$order = M('Order') -> where(array('id' => $order_id, 'status' => 2, 'confirm' => 0)) -> find();
		
		if(!$order){
			
			return false;
		}
		
		$Site_balance_logDB = D('Site_balance_log');
		
		$member = M('Member') -> where(array('id' => $order['member_id'])) -> find();
		
		//获取代理价格
		$num = strpos($order['Guestbook'],'终身版');
		if($num !== false){
			$num = 0;
		}else{
			$num = M('Sale') -> where(array('order_id' => $order['id'])) -> getField('num');
		}
		exit('xxx');
		$agentprice = D('Agentprice') -> getagentpricebylevel($order['siteid'], $num);
		//扣款成功后
		$r = $Site_balance_logDB -> change($agentprice*-1, __SITEID__, $member['nickname'].$order['Guestbook'], 0);
		if(!$r){
			M('Order') -> data(array('Guestbook' => $order['Guestbook'].'#'.$Site_balance_logDB -> getError().'#')) -> where(array('id' => $order_id, 'status' => 2, 'confirm' => 0)) -> save();
			return false;
		}
		
		 
		
		
		
		
		$num = M('Sale') -> where(array('order_id' => $order_id)) -> getField('num');
		$_POST['id'] = $order['siteid'];
		$_POST['timeout'] = $num;
		$_POST['copydata'] = array('Pages','Category','News','Product_category','Product','Intesys');
		$site = M('Site') -> where(array('id' => $order['siteid'])) -> find();
		$siteid = D('Site') -> copy();
		//写入一个会员信息，用当前创建这个站点的会员信息，加上权限后写入
		$Employee = $member;
		$Employee['copyid'] = $Employee['id'];
		unset($Employee['id']);
		$Employee['pid'] = 0;
		$Employee['site_id'] = $siteid;
		$Employee['isadministrator'] = 1;
		M('Member') -> add($Employee);
		
		//将会员信息保存至新站点配置中
		$siteConfig=unserialize(D('Site')->where(['id'=>$siteid])->getField('config'));
		$siteConfig['contact']=$member['name'];
		$siteConfig['phone']=$member['tel'];
		$siteConfig=serialize($siteConfig);
		
		//记录代理商ID，确定当前站点由哪个代理商开设，要进行代理扣款
		$formproduct_id = M('Sale') -> where(array('order_id' => $order['id'])) -> getField('product_id');
		$renewprice = M('Product') -> where(array('id' => $formproduct_id)) -> getField('systemagentrenewprice');
		$setagentidret = D('Site') -> where(array('id' => $siteid)) -> data(array('renewprice' => $renewprice,'formproduct_id' => $formproduct_id,'agentid' => $order['site_id'], 'siteid' => $order['siteid'], 'orderid' => $order_id, 'member_id' => $order['member_id'], 'balance' => 0,'config'=>$siteConfig,'maxNum'=>$order['maxNum'])) -> save();
		
		
		
	
		
		
		
		$pwd = rand(000000,999999);
		//创建用户
		$user['account'] = 'user'.$order['member_id'].time();
		$user['nickname'] = $member['nickname'] == '' ? '新用户' : $member['nickname']; 
		$user['status'] = 1;
		$user['member_id'] = $order['member_id'];
		$user['password'] = md5($pwd);
		$map['member_id'] = $order['member_id'];
		//用户是否存在
		$userdb = D('User');
		$cuser = $userdb -> where($map) -> find();
		if(!$cuser){
			$user_id = $userdb -> add($user);
			
			//分配权限
			$rolelist = explode(',', $site['roleid']);
			foreach($rolelist as $v){
				$roledata['user_id'] = $user_id;
				$roledata['role_id'] = $v;
				M('Role_user') -> add($roledata);
			}
			
			sendWXMsg($member['openid'], "您开通的站点是：http://".$_SERVER['HTTP_HOST']."/".$siteid."\r\n后台管理地址是：".U('Member/Index/manage', '', true, false, true, __SITEID__)."\r\n用户名：".$user['account']."\r\n密码：".$pwd);
		}else{
			$user_id = $cuser['id']; 
			sendWXMsg($member['openid'], "您开通的站点是：http://".$_SERVER['HTTP_HOST']."/".$siteid."\r\n后台管理地址是：".U('Member/Index/manage', '', true, false, true, __SITEID__));
		}
		//分配站点
		$site_user['user_id'] = $user_id;
		$site_user['site_id'] = $siteid;
		M('Site_user') -> add($site_user);
		//订单确认
		M('Order') -> where(array('id' => $order_id)) -> data(array('shipping_status' => 4, 'confirm' => 1)) -> save(); 
		M('Sale') -> where(array('order_id' => $order_id)) -> data(array('status' => 1, 'confirm' => 1)) -> save();
		M('Site') -> where(array('id' => $siteid)) -> data(array('status' => 1)) -> save();
	}
	
	
	//生成二维码
	public function qrcode(){
		vendor("phpqrcode.phpqrcode");
		if(isset($_GET['type']) && $_GET['type'] == 'url'){
			$_GET['data'] = base64_decode($_GET['data']);
		}
		$data = $_GET['data'];
		$level = $_GET['level'];
		$size = $_GET['size'];
        QRcode::png($data, false, $level, $size);
	}
	
	//获取订单状态,用于二维码支付时ajax轮询
	public function getOrderStatus(){
		$order_id = $this->_post('id');
		$ret = M('Order') -> where(array('id' => $order_id)) -> getField('status');
		echo $ret;
	}
	
	
    //异步返回当前开通站点的价格
	public function getSitePriceByNum(){
		$num = $this->_post('num');
		$product_id = $this->_post('id');
		$price = M('Product') -> where(array('id' => $product_id)) -> getField('systemagentprice');
		//$this->price = json_decode($price)); 
		$db = D('Agentprice');
		//记录个数，用COOKIE记录 
		setcookie('createsite'.__SITEID__, $product_id.'-'.$num, time() + 3600, '/');
		echo $db -> getprice($price, intval($num));
	}
	 
	//站点续费
	public function renewSite(){
		ignore_user_abort();
		$order_id = $this->_get('order_id');
		$order = M('Order') -> where(array('id' => $order_id, 'status' => 2, 'confirm' => 0, 'is_renew' => array('gt', 0))) -> find();
		if(!$order){
			return false;
		}
		$Site_balance_logDB = D('Site_balance_log');
		
		//$member = M('Member') -> where(array('id' => $order['member_id'])) -> find();
		
		//获取代理价格
		$num = strpos($order['Guestbook'],'终身版');
		if($num !== false){
			$num = 600;
		}else{
			$num = M('Sale') -> where(array('order_id' => $order['id'])) -> getField('num');
		}
		$site = M('Site') -> where(array('id' => $order['is_renew'])) -> find();
		
		
		//传入当时开通复制的站点进行续费扣款计算
		$agentprice = D('Agentprice') -> getagentrenewpricebylevel($site['siteid'], $num);
		//F('ws1', $agentprice);
		//扣款成功后
		$r = $Site_balance_logDB -> change($agentprice*-1, __SITEID__, $member['nickname'].$order['Guestbook'], 0);
		if(!$r){
			M('Order') -> data(array('Guestbook' => $order['Guestbook'].'#'.$Site_balance_logDB -> getError().'#')) -> where(array('id' => $order_id, 'status' => 2, 'confirm' => 0)) -> save();
			return false;
		}
		//扣款
		
		
		
		if($site['timeout'] < time()){
			$data['timeout'] = time() + 3600*24*30*$num;
		}else{
			$data['timeout'] = $site['timeout']*1+3600*24*30*$num;
		}
		
		M('Site') -> where(array('id' => $order['is_renew'])) -> save($data);
		
		
		//订单确认
		M('Order') -> where(array('id' => $order_id)) -> data(array('shipping_status' => 4, 'confirm' => 1)) -> save(); 
		M('Sale') -> where(array('order_id' => $order_id)) -> data(array('status' => 1, 'confirm' => 1)) -> save();
	}
	
	//检查一个订单的站点是否已经开通完毕
	public function createSiteCheck(){
		$order_id = $this->_post('order_id');
		$site = M('Site') -> where(array('orderid' => $order_id, 'status' => 1)) -> find();
		if($site){
			$this->success('站点正常！');
		}else{
			//看看是不是平台扣款失败没有开通
			//查找订单
			$order = M('Order')->where(array('id' => $order_id, 'site_id' => __SITEID__)) -> find();
			if($order['status'] != 2){
				$this->error('订单还没有支付！');
				exit;
			}
			if(strpos($order['Guestbook'], '扣款失败') > 0){
				$this->error('系统繁忙！系统未开通，请联系客服人员开通！谢谢！');
				exit;
			}
			$this->error('进程可能还在处理，请稍等……');
		}
	}
	
}